package com.hbnu.dao;



import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;

import static com.hbnu.enums.Status.*;

public abstract class JDBC {
    protected  Connection connection;
    {
        try {
            connection = DriverManager.getConnection(url,user,password);
        }catch (SQLException e){
            throw new RuntimeException("数据库连接失败....");
        }
    }



    //Statement.RETURN_GENERATED_KEYS

    protected Statement getStatement() throws SQLException {
        return connection.createStatement();
    }
    protected PreparedStatement getPreparedStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }
    protected PreparedStatement getPreparedStatement0(String sql) throws SQLException {
        return connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
    }

    @SuppressWarnings("unchecked")
     <T> T to(ResultSet set,Class<T> tClass)  {
        try {
            Constructor<?>[] declaredConstructors = tClass.getDeclaredConstructors();
            //所有参数
            Class<?>[] parameterTypes = declaredConstructors[0].getParameterTypes();
            Object[] parameter = new Object[parameterTypes.length];
            for (int i = 0; i < parameter.length; i++) {
                parameter[i] = set.getObject(i + 1);
                if(parameter[i]==null) continue;
                if (parameter[i].getClass() != parameterTypes[i])
                    if(parameterTypes[i]==Boolean.class){
                        Integer integer = (Integer) parameter[i];  // 获取为 Integer 类型
                        // 转换为 Boolean
                        parameter[i] = integer == 1;
                    }
                    else throw new SQLException("错误的类型转换：" + parameter[i].getClass() + " -> " + parameterTypes[i]);
            }
            return (T) declaredConstructors[0].newInstance(parameter);
        }catch (SQLException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
